package com.yin.good.service;

import java.util.Date;
import java.util.UUID;

import javax.transaction.Transactional;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yin.good.entity.GoodInfoEntity;
import com.yin.good.jpa.GoodInfoJPA;
import com.yin.timer.GoodAddTimer;
import com.yin.timer.GoodStockCheckTimer;

/**
*@author LSY
*Time: 2018年12月28日下午4:19:11
*
*
*/
@Service
@Transactional(rollbackOn = Exception.class)
public class GoodInfoService {

	@Autowired
	private GoodInfoJPA goodInfoJPA;
	
	@Autowired
	private Scheduler scheduler;
	
	public Long saveGood(GoodInfoEntity good) throws Exception {
		goodInfoJPA.save(good);
		//构建创建商品定时任务
		buildCreateGoodTimer();
		 //构建商品库存定时任务
		buildGoodStockTimer();
		
		return good.getId();
	}
	//创建定时任务
	public void buildCreateGoodTimer() throws SchedulerException {
		//开始时间为半分钟后
		long startTime = System.currentTimeMillis() + 1000 * 30;
		//任务名称
		String name = UUID.randomUUID().toString();
		//任务分组
		String group = GoodAddTimer.class.getName();
		//创建任务
		JobDetail jobDetail = JobBuilder.newJob(GoodAddTimer.class).withIdentity(name, group).build();
		//创建触发器
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).startAt(new Date(startTime)).build();
		//将触发器与任务绑定到调度器内
		scheduler.scheduleJob(jobDetail, trigger);
	}
	
	public void buildGoodStockTimer() throws Exception{
		//任务名称
		String name = UUID.randomUUID().toString();
		//任务分组
		String group = GoodStockCheckTimer.class.getName();
		
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/30 * * * * ?");
		//创建任务
		JobDetail jobDetail = JobBuilder.newJob(GoodStockCheckTimer.class).withIdentity(name, group).build();
		//创建触发器
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).withSchedule(scheduleBuilder ).build();
		//将触发器与任务绑定到调度器内
		scheduler.scheduleJob(jobDetail, trigger);
	}
	
}
